package com.example.shop.common.service.impl;

import com.aliyun.sdk.service.dysmsapi20170525.AsyncClient;
import com.aliyun.sdk.service.dysmsapi20170525.models.SendSmsRequest;
import com.aliyun.sdk.service.dysmsapi20170525.models.SendSmsResponse;
import com.aliyun.sdk.service.dysmsapi20170525.models.SendSmsResponseBody;
import com.example.shop.common.dto.sms.ShortMessage;
import com.example.shop.common.service.SMSService;
import com.fasterxml.jackson.core.JsonProcessingException;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.google.gson.Gson;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.concurrent.CompletableFuture;
import java.util.concurrent.ExecutionException;
import java.util.concurrent.TimeUnit;
import java.util.concurrent.TimeoutException;
import java.util.function.Consumer;
import java.util.function.Function;

@Service
public class SMSServiceImpl implements SMSService {

    @Autowired
    AsyncClient smsAsyncSendClient;


    @Override
    public void asyncSendSms(ShortMessage shortMessage,
            Consumer<? super SendSmsResponse> success,Function<Throwable, ? extends Void> error){
        SendSmsRequest request=SendSmsRequest.builder()
                .phoneNumbers(shortMessage.getAcceptPhoneNumber())
                .signName(shortMessage.getSignName())
                .templateCode(shortMessage.getTemplateCode())
                .templateParam(shortMessage.getTemplateParam())
                .outId(shortMessage.getOutId())
                .build();

        CompletableFuture<SendSmsResponse> response = smsAsyncSendClient.sendSms(request);
        //对返回值的异步处理
        response.thenAccept(success).exceptionally(error);
    }

    @Override
    public SendSmsResponseBody sendSms(ShortMessage shortMessage) {
        SendSmsRequest request=SendSmsRequest.builder()
                .phoneNumbers(shortMessage.getAcceptPhoneNumber())
                .signName(shortMessage.getSignName())
                .templateCode(shortMessage.getTemplateCode())
                .templateParam(shortMessage.getTemplateParam())
                .outId(shortMessage.getOutId())
                .build();

        CompletableFuture<SendSmsResponse> response = smsAsyncSendClient.sendSms(request);
        SendSmsResponse resp = null;
        try {
            resp = response.get(5, TimeUnit.SECONDS);
        } catch (Exception e) {
            e.printStackTrace();
        }
        if(resp!=null){
            return resp.getBody();
        }
        return null;
    }
}
